import axios from 'axios'
import {Dialog, Toast} from 'vant';
import {getLocal, removeLocal} from "@/common/js/local-storge";

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000,
})

service.interceptors.request.use(req => {

    const token = getLocal("token");
    console.log("token: ", token)
    if (token != null) {
        req.headers["Authorization"] = "Bearer " + token;
    }

    console.log("req: ",req)
    return req
})

service.interceptors.response.use(
    res => {
        // 状态码处理
        let status = res.data.code ? res.data.code : 0;
        console.log('状态码', status)
        switch (status) {
            case 200:
                console.log('res.data: ', res.data)
                return res.data
            case 403:
                Toast.fail('权限校验失败')
                break
            case 500:
                Toast.fail('服务器错误')
                break
            default:
                break
        }
    },
    error => {
        console.log('err' + error)// for debug
        Dialog.alert({
            title: '警告',
            message: '登录连接超时，请重新登录'
        }).then(() => {
            removeLocal("token")
            removeLocal("userId")
            window.location.href = '/'
        });
        return Promise.reject(error)
    }
)

export default service